﻿using System.Net;
using Newtonsoft.Json;

namespace NiuX.AspNetCore.Middlewares;

public class ErrorHandlingMiddleware
{
    private readonly RequestDelegate next;
    private readonly ILogger _logger;

    public ErrorHandlingMiddleware(RequestDelegate next, ILogger logger)
    {
        this.next = next;
        _logger = logger;
    }
    public async Task Invoke(HttpContext context /* other dependencies */)
    {
        try
        {
            await next(context);
        }
        catch (Exception ex)
        {
            await HandleExceptionAsync(context, ex);
        }

    }

    private Task HandleExceptionAsync(HttpContext context, Exception ex)
    {
        _logger.LogError(ex, ex.Message);

        var code = HttpStatusCode.InternalServerError; // 500 if unexpected
        var Info = "";
        switch (context.Response.StatusCode)
        {
            case 401:
                Info = "没有权限";
                break;
            case 404:
                Info = "未找到服务";
                break;
            case 403:
                Info = "服务器理解请求客户端的请求，但是拒绝执行此请求";
                break;
            case 500:
                Info = "服务器内部错误，无法完成请求";
                break;
            case 502:
                Info = "请求错误";
                break;
            default:
                Info = "内部错误";
                break;
        }
        
        var result = JsonConvert.SerializeObject(new { error = ex.Message });
        context.Response.ContentType = "application/json";
        context.Response.StatusCode = (int)code;
        return context.Response.WriteAsync(result);
    }
}